import React, { useState, useEffect } from 'react';
import { MailOutlined, WechatOutlined, DingdingOutlined, EyeInvisibleOutlined, EyeTwoTone, MinusCircleOutlined, PlusOutlined, EditOutlined } from '@ant-design/icons';
import { Modal, Form, Input, Tabs, Radio, Button, InputNumber, Checkbox, message, TimePicker, Spin, Row, Col, Tag } from 'antd';
import moment from 'moment';
import { FormInstance } from 'antd/lib/form';
import { OrgItem, OrgTimeItem } from '../data';
import { getAlertDetail, setEmailAlert, setWeChatUserAlert, setWeChatGroupAlert, setDingDingAlert } from '../service';
import styles from '../index.less';

interface CreateFormProps {
  modalVisible: boolean;
  onCancel: () => void;
  onSubmit: () => void;
  values: OrgItem;
}

const { TabPane } = Tabs;

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

const layout1 = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};

const layout2 = {
  labelCol: { span: 0 },
  wrapperCol: { span: 24 },
};

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};

const formItemLayoutWithOutLabel = {
  wrapperCol: {
    xs: { span: 24, offset: 0 },
    sm: { span: 16, offset: 6 },
  },
};

const CheckboxGroup = Checkbox.Group;

const weeksObject = {
  MONDAY: '星期一',
  TUESDAY: '星期二',
  WEDNESDAY: '星期三',
  THURSDAY: '星期四',
  FRIDAY: '星期五',
  SATURDAY: '星期六',
  SUNDAY: '星期日',
}
const weeks = [
  { value: 'MONDAY', label: '星期一' },
  { value: 'TUESDAY', label: '星期二' },
  { value: 'WEDNESDAY', label: '星期三' },
  { value: 'THURSDAY', label: '星期四' },
  { value: 'FRIDAY', label: '星期五' },
  { value: 'SATURDAY', label: '星期六' },
  { value: 'SUNDAY', label: '星期日' }
]
const formRef = React.createRef<FormInstance>();

const SetOrgModel: React.FC<CreateFormProps> = (props) => {
  const { modalVisible, onSubmit, onCancel, values } = props;
  const [tab, setTab] = useState<string>("1");
  const [activeKey, setActiveKey] = useState<string>("1");
  const [loading, setLoading] = useState<boolean>(false);
  const [spinning, setSpinning] = useState<boolean>(false);
  const [dialogVisible, setDialogVisible] = useState<boolean>(false);
  const [access, setAccess] = useState<string>("");
  const [mail, setMail] = useState<OrgTimeItem>();
  const [wechatUser, setWechatUser] = useState<OrgTimeItem>();
  const [wechatGroup, setWechatGroup] = useState<OrgTimeItem>();
  const [dingding, setDingDing] = useState<OrgTimeItem>();

  const [checkedList, setCheckedList] = React.useState([]);
  const [indeterminate, setIndeterminate] = React.useState(true);
  const [checkAll, setCheckAll] = React.useState(false);

  const [form] = Form.useForm();
  const [form1] = Form.useForm();
  const [form2] = Form.useForm();
  const [form3] = Form.useForm();
  const [form4] = Form.useForm();

  useEffect(() => {
    if (modalVisible) {
      const weChatUserIdsEmpty = [{
        fieldKey: 0,
        isListField: true,
        key: 0,
        name: 0,
        wechatUserId: "",
      }];
      const alertEmailToEmpty = [{
        fieldKey: 0,
        isListField: true,
        key: 0,
        name: 0,
        alertEmailTo: "",
      }];
      if (values && values.id) {
        setTab("1");
        setSpinning(true);
        new Promise((resolve, reject) => {
          getAlertDetail(values.id)
            .then((res) => {
              if (res.code === 200) {
                const data = res.data;
                //报警邮箱初始化
                const alertEmail =  data.email;
                const alertEmailEnable = alertEmail.alertEnabled;
                if(alertEmail.alertEmailServer){
                  const alertEmailTo = alertEmail.alertEmailTo.split(",");
                  const alertEmailTos = [];
                  alertEmailTo.map((item, index) => {
                    let temp = new Object;
                    temp["isListField"] = true;
                    temp["fieldKey"] = index;
                    temp["key"] = index;
                    temp["name"] = index;
                    temp["alertEmailTo"] = item;
                    alertEmailTos.push(temp);
                  });
                  alertEmail["alertEmailTo"] = alertEmailTos;
                  form.setFieldsValue(alertEmail);
                }else {
                  form.resetFields();
                  form.setFieldsValue({
                    orgId: values.id,
                    alertEmailTo: alertEmailToEmpty,
                  });
                }
                form.setFieldsValue({ "alertEnabled": alertEmailEnable ? alertEmailEnable : false });
                if(alertEmailEnable){
                  alertEmail.alertTriggerHour = parseInt(alertEmail.alertTriggerTime.split(":")[0]);
                  alertEmail.alertTriggerMinute = parseInt(alertEmail.alertTriggerTime.split(":")[1]);
                  setMail(alertEmail);
                }
                //企业微信--应用发送初始化
                const alertWechatUser = data.wechatUser;
                const alertWechatUserEnable = alertWechatUser.alertEnabled;
                if(alertWechatUser.wechatCompanyId){ 
                  const wechatUserId = alertWechatUser.wechatUserId.split(",");
                  const wechatUserIds = [];
                  wechatUserId.map((item, index) => {
                    let temp = new Object;
                    temp["isListField"] = true;
                    temp["fieldKey"] = index;
                    temp["key"] = index;
                    temp["name"] = index;
                    temp["wechatUserId"] = item;
                    wechatUserIds.push(temp);
                  });
                  alertWechatUser["wechatUserId"] = wechatUserIds;
                  form1.setFieldsValue(alertWechatUser);
                } else {
                  form1.resetFields();
                  form1.setFieldsValue({
                    orgId: values.id,
                    wechatUserId: weChatUserIdsEmpty,
                  });
                }
                form1.setFieldsValue({ "alertEnabled": alertWechatUserEnable ? alertWechatUserEnable : false });
                if(alertWechatUserEnable){
                  alertWechatUser.alertTriggerHour = parseInt(alertWechatUser.alertTriggerTime.split(":")[0]);
                  alertWechatUser.alertTriggerMinute = parseInt(alertWechatUser.alertTriggerTime.split(":")[1]);
                  setWechatUser(alertWechatUser);
                }
                //企业微信--群组发送初始化
                const alertWechatGroup = data.wechatGroup;
                const alertWechatGroupEnable = alertWechatGroup.alertEnabled;
                if(alertWechatGroupEnable){
                  alertWechatGroup.alertTriggerHour = parseInt(alertWechatGroup.alertTriggerTime.split(":")[0]);
                  alertWechatGroup.alertTriggerMinute = parseInt(alertWechatGroup.alertTriggerTime.split(":")[1]);
                  setWechatGroup(alertWechatGroup);
                }else{
                  form2.resetFields();
                }
                form2.setFieldsValue({
                  "orgId": values.id,
                  "wechatWebHook":alertWechatGroup.wechatWebHook,
                  "alertEnabled": alertWechatGroupEnable ? alertWechatGroupEnable : false 
                });
                //钉钉初始化
                const alertDingDing = data.dingding;
                const alertDingDingEnable = alertDingDing.alertEnabled;
                if(alertDingDingEnable){
                  alertDingDing.alertTriggerHour = parseInt(alertDingDing.alertTriggerTime.split(":")[0]);
                  alertDingDing.alertTriggerMinute = parseInt(alertDingDing.alertTriggerTime.split(":")[1]);
                  setDingDing(alertDingDing);
                }else{
                  form3.resetFields();
                }
                form3.setFieldsValue({ 
                  "orgId": values.id,
                  "dingdingWebHook":alertDingDing.dingdingWebHook,
                  "alertEnabled": alertDingDingEnable ? alertDingDingEnable : false 
                });
                
                resolve(true);
              } else {
                message.error('请求失败，' + res.message);
                resolve(false);
              }
              setSpinning(false);
            })
            .catch((error) => {
              setSpinning(false);
              message.error('请求失败');
              reject(error);
            });
        });
      }
    }else{
      setMail("");
      setWechatUser("");
      setWechatGroup("");
      setDingDing("");
    }
  }, [modalVisible]);

  useEffect(() => {
    if (dialogVisible) {

    } else {
      setCheckedList([]);
      setIndeterminate(false);
      setCheckAll(false);
      form4.resetFields();
    }
  }, [dialogVisible]);

  useEffect(() => {
    form4.setFieldsValue({ "alertDate": checkedList });
  }, [checkedList]);

  const handleEmailFinish = (values: { [key: string]: any }) => {
    setLoading(true);
    values.alertEmailUsername = values.alertEmailFrom.split("@")[0];
    new Promise((resolve, reject) => {
      const alertEmailTo = [];
      values.alertEmailTo.map((item, index) => {
        alertEmailTo.push(item.alertEmailTo)
      });
      values["alertEmailTo"] = alertEmailTo.toString();
      values["alertDate"] = mail?.alertDate;
      values["alertStartTime"] = mail?.alertStartTime;
      values["alertEndTime"] = mail?.alertEndTime;
      values["alertTriggerTime"] = mail?.alertTriggerTime;
      setEmailAlert(values)
        .then((res) => {
          setLoading(false);
          if (res.code === 200) {
            message.success('报警邮箱 设置成功');
            onSubmit();
            resolve(true);
          } else {
            message.error('请求失败，' + res.message);
            resolve(false);
          }
        })
        .catch((error) => {
          setLoading(false);
          message.error('请求失败');
          reject(error);
        });
    });
  };

  const handleWeChatFinish = (values: { [key: string]: any }) => {
    setLoading(true);
    new Promise((resolve, reject) => {
      const wechatUserId = [];
      values.wechatUserId.map((item, index) => {
        wechatUserId.push(item.wechatUserId)
      });
      values["wechatUserId"] = wechatUserId.toString();
      values["alertDate"] = wechatUser?.alertDate;
      values["alertStartTime"] = wechatUser?.alertStartTime;
      values["alertEndTime"] = wechatUser?.alertEndTime;
      values["alertTriggerTime"] = wechatUser?.alertTriggerTime;
      setWeChatUserAlert(values)
        .then((res) => {
          setLoading(false);
          if (res.code === 200) {
            message.success('企业微信--应用发送 设置成功');
            onSubmit();
            resolve(true);
          } else {
            message.error('请求失败，' + res.message);
            resolve(false);
          }
        })
        .catch((error) => {
          setLoading(false);
          message.error('请求失败');
          reject(error);
        });
    });
  };
  const handleWeChatHookFinish = (values: { [key: string]: any }) => {
    setLoading(true);
    new Promise((resolve, reject) => {
      values["alertDate"] = wechatGroup?.alertDate;
      values["alertStartTime"] = wechatGroup?.alertStartTime;
      values["alertEndTime"] = wechatGroup?.alertEndTime;
      values["alertTriggerTime"] = wechatGroup?.alertTriggerTime;
      setWeChatGroupAlert(values)
        .then((res) => {
          setLoading(false);
          if (res.code === 200) {
            message.success('企业微信--群组发送 设置成功');
            onSubmit();
            resolve(true);
          } else {
            message.error('请求失败，' + res.message);
            resolve(false);
          }
        })
        .catch((error) => {
          setLoading(false);
          message.error('请求失败');
          reject(error);
        });
    });
  };

  const setScroll = () => {
    setTimeout(function () {
      const body = document.getElementsByClassName("wechatUserId")[0];
      const height = body?.querySelector('.content')?.clientHeight;
      if (height && height > 160) {
        body.scrollTop = height;
      }
    }, 0)
  }

  const handleUpdate = () => {
    if (tab == "1") {
      if (!form) return;
      form.submit();
    } else if (tab == "2") {
      if(activeKey == "3"){
        if (!form1) return;
        form1.submit();
      }else if (activeKey == "4") {
        if (!form2) return;
        form2.submit();
      } 
    } else if (tab == "5") {
      if (!form3) return;
      form3.submit();
    }
  };

  const callback = (key: string) => {
    if (key == "2") {
      setActiveKey("3");
    }
    setTab(key);
  }

  const callback1 = (key: string) => {
    setActiveKey(key);
  }

  const modalFooter = { okText: '保存', onOk: handleUpdate, onCancel: onCancel };

  const IsURL = (str_url: string) => {
    var strRegex = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/;
    var re = new RegExp(strRegex);
    if (re.test(str_url)) {
      return (true);
    } else {
      return (false);
    }
  }
  const sslChange = (e: Event) => {
    const value = e.target.checked;
    form.setFieldsValue({ "alertEmailSslEnable": value })
  }

  const handleDingDingHookFinish = (values: { [key: string]: any }) => {
    setLoading(true);
    new Promise((resolve, reject) => {
      values["alertDate"] = dingding?.alertDate;
      values["alertStartTime"] = dingding?.alertStartTime;
      values["alertEndTime"] = dingding?.alertEndTime;
      values["alertTriggerTime"] = dingding?.alertTriggerTime;
      setDingDingAlert(values)
        .then((res) => {
          setLoading(false);
          if (res.code === 200) {
            message.success('钉钉 设置成功');
            onSubmit();
            resolve(true);
          } else {
            message.error('请求失败，' + res.message);
            resolve(false);
          }
        })
        .catch((error) => {
          setLoading(false);
          message.error('请求失败');
          reject(error);
        });
    });
  }

  const noticeChange = (e: Event) => {
    setAccess('add');
    const value = e.target.value;
    const name =  e.target.name;
    if (value) {
      form4.setFieldsValue({ "orgId": values.id, "alertType": name})
      setDialogVisible(true);
    }else{
      switch(name){
      case 'EMAIL':
        setMail("");
        break;
      case 'WECHATUSER':
        setWechatUser("");
        break;
      case 'WECHATGROUP':
        setWechatGroup("");
        break;
      case 'DINGDING':
        setDingDing("");
        break;
      default:
        break;
      }
    }
  }
  const onDateChange = (list) => {
    setCheckedList(list);
    setIndeterminate(!!list.length && list.length < weeks.length);
    setCheckAll(list.length === weeks.length);
  }
  const onCheckAllChange = e => {
    setCheckedList(e.target.checked ? weeks.map(item => item.value) : []);
    setIndeterminate(false);
    setCheckAll(e.target.checked);
  };

  const rangePickerChange = (value: any, dateString: string) => { //计划日期
    if (dateString) {
      form4.setFieldsValue({ "alertStartTime": dateString[0], "alertEndTime": dateString[1] });
    }
  }

  const handleSetNoticeTime = (values: OrgTimeItem) => {
    console.log(values)
    const alertTriggerHour = values.alertTriggerHour;
    const alertTriggerMinute = values.alertTriggerMinute;
    values.alertTriggerTime = (alertTriggerHour > 9 ? alertTriggerHour : `0${alertTriggerHour}`) + ":" + alertTriggerMinute;
    setDialogVisible(false);
    switch (values.alertType) {
      case 'EMAIL':
        setMail(values);
        break;
      case 'WECHATUSER':
        setWechatUser(values);
        break;
      case 'WECHATGROUP':
        setWechatGroup(values);
        break;
      case 'DINGDING':
        setDingDing(values);
        break;
      default:
        break;
    }
  }

  const setTimeSubmit = () => {
    if (!form4) return;
    form4.submit();
  }

  const dialogClose = () => {
    const alertType = form4.getFieldValue("alertType");
    switch (alertType) {
      case 'EMAIL':
        if(access == 'add'){
          form.setFieldsValue({"alertEnabled":false});
        }
        break;
      case 'WECHATUSER':
        if(access == 'add'){
          form1.setFieldsValue({"alertEnabled":false});
        }
        break;
      case 'WECHATGROUP':
        if(access == 'add'){
          form2.setFieldsValue({"alertEnabled":false});
        }
        break;
      case 'DINGDING':
        if(access == 'add'){
          form3.setFieldsValue({"alertEnabled":false});
        }
        break;
      default:
        break;
    }
    setDialogVisible(false);
  }
  const renderContent = () => {
    return (
      <>
        <Tabs onChange={callback} type="card">
          <TabPane tab={<span><MailOutlined />报警邮箱</span>} key="1">
            <Form {...layout} ref={formRef} form={form} onFinish={handleEmailFinish}>
              <Form.Item name="orgId" style={{ display: 'none' }}></Form.Item>
              <Form.Item
                name="alertEmailServer"
                label="服务器地址"
                rules={[{ required: true, max: 64 }]}
              >
                <Input placeholder="请输入服务器地址" />
              </Form.Item>
              <Form.Item
                name="alertEmailPort"
                label="端口号"
                rules={[{ required: true }]}
              >
                <InputNumber min={0} max={65535} defaultValue={0} placeholder="请输入服务器端口号" />
              </Form.Item>
              <Form.Item
                name="alertEmailFrom"
                label="发件人邮箱地址"
                rules={[{ required: true, max: 64, type: "email" }]}
              >
                <Input placeholder="请输入发件人邮箱地址" />
              </Form.Item>
              <Form.Item
                name="alertEmailUsername"
                label="邮箱用户名"
                hidden={true}
              >
                <Input placeholder="请输入邮箱用户名" />
              </Form.Item>
              <Form.Item
                name="alertEmailPassword"
                label="邮箱授权码"
                rules={[{ required: true, max: 64 }]}
              >
                <Input.Password
                  placeholder="请输入邮箱授权码"
                  iconRender={visible => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
                  style={{ width: 'calc(100% - 30px)' }}
                  autoComplete="new-password"
                />
              </Form.Item>
              {/* <Form.Item
              name="alertEmailCondition"
              label="推送条件"
              initialValue={30}
            >
              <Radio.Group>
                <Radio value={30}>设置短期掉线</Radio>
                <Radio value={480}>设置长期掉线</Radio>
              </Radio.Group>
            </Form.Item> */}
              <Form.Item
                name="alertEmailSslEnable"
                label="是否启用SSL"
                initialValue={false}
                valuePropName="checked"
              >
                <Checkbox onChange={sslChange}>启用</Checkbox>
              </Form.Item>
              <Form.Item
                name="alertEnabled"
                label="异常通知时间设置"
                initialValue={false}
                style={{marginBottom:0}}
              >
                <Radio.Group name="EMAIL" onChange={noticeChange}>
                  <Radio value={true}>启用</Radio>
                  <Radio value={false}>禁用</Radio>
                </Radio.Group>
              </Form.Item>
              <Form.Item
                noStyle
                shouldUpdate={(prevValues, currentValues) =>
                  prevValues.resolution !== currentValues.resolution
                }
              >
                {({ getFieldValue }) => {
                  return mail?.alertDate ? (
                    <>
                      <div className="pop">
                        <div className="mask">
                          <div className="content" onClick={() =>{
                            mail.alertTime = [moment(mail?.alertStartTime,'HH:mm:ss'), moment(mail?.alertEndTime,'HH:mm:ss')];
                            mail.alertType = "EMAIL";
                            console.log(mail)
                            form4.setFieldsValue(mail);
                            setCheckedList(mail.alertDate);
                            setIndeterminate(!!mail.alertDate.length && mail.alertDate.length < weeks.length);
                            setCheckAll(mail.alertDate.length === weeks.length);
                            setAccess("edit");
                            setDialogVisible(true);
                          }} 
                          >
                            <span className="button">
                              <EditOutlined style={{ fontSize: 32 }} />
                              <span style={{ display: 'block', marginTop: 5, fontSize: 16 }}>编辑</span>
                            </span>
                          </div>
                        </div>
                        <Row>
                          <Col span={6}>预警日期:</Col>
                          <Col span={16}>{mail.alertDate.map(date => { return <Tag color="blue" style={{ marginBottom: 5 }}>{weeksObject[date]}</Tag> })}</Col>
                        </Row>
                        <Row>
                          <Col span={6}>预警时间:</Col>
                          <Col span={16}>{mail.alertStartTime} - {mail.alertEndTime}</Col>
                        </Row>
                        <Row>
                          <Col span={6}>超时时间:</Col>
                          <Col span={16}>{mail.alertTriggerTime}</Col>
                        </Row>
                      </div>
                    </>
                  ) : null;
                }}
              </Form.Item>
              <hr />
              <Form.List
                name="alertEmailTo"
              >
                {(fields, { add, remove }) => (
                  <>
                    <span className="wechatUserId">
                      <div className="content">
                        {fields.map((field, index) => (
                          <Form.Item
                            {...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
                            label={index === 0 ? '收件人邮箱地址' : ''}
                            required={true}
                            key={field.key}
                          >
                            <Form.Item
                              {...field}
                              name={[field.name, 'alertEmailTo']}
                              fieldKey={[field.fieldKey, 'alertEmailTo']}
                              rules={[{ type: 'email', message: '收件人邮箱地址不是一个有效的email' }, {
                                validator: (rule, value, callback) => {
                                  if (!value) {
                                    callback("请输入收件人邮箱地址");
                                    return;
                                  }
                                  if (value.length > 64) {
                                    callback("收件人邮箱地址最多64个字符");
                                  } else {
                                    callback();
                                  }
                                },
                              }
                              ]}
                              noStyle
                            >
                              <Input placeholder="请输入收件人邮箱地址" />
                            </Form.Item>
                            {fields.length > 1 ? (
                              <MinusCircleOutlined
                                className="deleteButton"
                                onClick={() => { remove(field.name) }}
                              />
                            ) : null}
                          </Form.Item>
                        ))}
                      </div>
                    </span>
                    <Form.Item {...formItemLayoutWithOutLabel} style={{marginBottom:0}}>
                      <Button
                        type="dashed"
                        onClick={() => {
                          add();
                          setScroll();
                        }}
                        icon={<PlusOutlined />}
                      >
                        添加收件人邮箱地址
                      </Button>
                    </Form.Item>
                  </>
                )}
              </Form.List>
            </Form>
          </TabPane>
          <TabPane tab={<span><WechatOutlined />企业微信</span>} key="2">
            <Tabs activeKey={activeKey} onChange={callback1} type="card">
              <TabPane tab="应用发送" key="3">
                <Form {...layout} ref={formRef} form={form1} onFinish={handleWeChatFinish}>
                  <Form.Item name="orgId" style={{ display: 'none' }}></Form.Item>
                  <Form.Item
                    name="wechatCompanyId"
                    label="企业ID"
                    rules={[{ required: true, max: 64, whitespace: true }]}
                  >
                    <Input placeholder="请输入企业ID" />
                  </Form.Item>
                  <Form.Item
                    name="wechatAppId"
                    label="应用ID"
                    rules={[{
                      required: true,
                      pattern: /(^[1-9]\d*$)/,
                      whitespace: true,
                      message: '必须为正整数'
                    }]}
                  >
                    <Input placeholder="请输入应用ID" maxLength={16} />
                  </Form.Item>
                  <Form.Item
                    name="wechatAppSecret"
                    label="应用secret"
                    rules={[{ required: true, max: 64, whitespace: true }]}
                  >
                    <Input placeholder="请输入应用secret" />
                  </Form.Item>
                  <Form.List
                    name="wechatUserId"
                  >
                    {(fields, { add, remove }) => (
                      <>
                        <span className="wechatUserId">
                          <div className="content">
                            {fields.map((field, index) => (
                              <Form.Item
                                {...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
                                label={index === 0 ? '用户ID' : ''}
                                required={true}
                                key={field.key}
                              >
                                <Form.Item
                                  {...field}
                                  name={[field.name, 'wechatUserId']}
                                  fieldKey={[field.fieldKey, 'wechatUserId']}
                                  rules={[{
                                    validator: (rule, value, callback) => {
                                      if (!value) {
                                        callback("请输入用户ID");
                                        return;
                                      }
                                      if (value.length > 64) {
                                        callback("用户ID最多64个字符");
                                      } else {
                                        callback();
                                      }
                                    },
                                  }
                                  ]}
                                  noStyle
                                >
                                  <Input placeholder="请输入用户ID" />
                                </Form.Item>
                                {fields.length > 1 ? (
                                  <MinusCircleOutlined
                                    className="deleteButton"
                                    onClick={() => { remove(field.name) }}
                                  />
                                ) : null}
                              </Form.Item>
                            ))}
                          </div>
                        </span>
                        <Form.Item {...formItemLayoutWithOutLabel}>
                          <Button
                            type="dashed"
                            onClick={() => {
                              add();
                              setScroll();
                            }}
                            icon={<PlusOutlined />}
                          >
                            添加用户ID
                          </Button>
                        </Form.Item>
                      </>
                    )}
                  </Form.List>
                  {/* <Form.Item
                      name="wechatUserCondition"
                      label="推送条件"
                      initialValue={30}
                    >
                      <Radio.Group >
                        <Radio value={30}>设置短期掉线</Radio>
                        <Radio value={480}>设置长期掉线</Radio>
                      </Radio.Group>
                  </Form.Item> */}
                  <Form.Item
                    name="alertEnabled"
                    label="异常通知时间设置"
                    initialValue={false}
                    style={{marginBottom:0}}
                  >
                    <Radio.Group name="WECHATUSER" onChange={noticeChange}>
                      <Radio value={true}>启用</Radio>
                      <Radio value={false}>禁用</Radio>
                    </Radio.Group>
                  </Form.Item>
                  <Form.Item
                    noStyle
                    shouldUpdate={(prevValues, currentValues) =>
                      prevValues.resolution !== currentValues.resolution
                    }
                  >
                    {({ getFieldValue }) => {
                      return wechatUser?.alertDate ? (
                        <>
                          <div className="pop">
                            <div className="mask">
                              <div className="content" onClick={() =>{
                                wechatUser.alertTime = [moment(wechatUser?.alertStartTime,'HH:mm:ss'), moment(wechatUser?.alertEndTime,'HH:mm:ss')];
                                wechatUser.alertType = "WECHATUSER";
                                form4.setFieldsValue(wechatUser);
                                setCheckedList(wechatUser.alertDate);
                                setIndeterminate(!!wechatUser.alertDate.length && wechatUser.alertDate.length < weeks.length);
                                setCheckAll(wechatUser.alertDate.length === weeks.length);
                                setAccess("edit");
                                setDialogVisible(true);
                              }} 
                              >
                                <span className="button">
                                  <EditOutlined style={{ fontSize: 32 }} />
                                  <span style={{ display: 'block', marginTop: 5, fontSize: 16 }}>编辑</span>
                                </span>
                              </div>
                            </div>
                            <Row>
                              <Col span={6}>预警日期:</Col>
                              <Col span={16}>{wechatUser.alertDate.map(date => { return <Tag color="blue" style={{ marginBottom: 5 }}>{weeksObject[date]}</Tag> })}</Col>
                            </Row>
                            <Row>
                              <Col span={6}>预警时间:</Col>
                              <Col span={16}>{wechatUser.alertStartTime} - {wechatUser.alertEndTime}</Col>
                            </Row>
                            <Row>
                              <Col span={6}>超时时间:</Col>
                              <Col span={16}>{wechatUser.alertTriggerTime}</Col>
                            </Row>
                          </div>
                        </>
                      ) : null;
                    }}
                  </Form.Item>
                </Form>
              </TabPane>
              <TabPane tab="群组发送" key="4">
                <Form {...layout1} ref={formRef} form={form2} onFinish={handleWeChatHookFinish}>
                  <Form.Item name="orgId" style={{ display: 'none' }}></Form.Item>
                  <Form.Item
                    name="wechatWebHook"
                    label="机器人webhook地址"
                    rules={[{ required: true, max: 256 }, {
                      validator: (rule, value, callback) => {
                        if (!value) {
                          callback();
                        }
                        if (IsURL(value)) {
                          callback();
                        } else {
                          callback("不是一个有效的地址");
                        }
                      },
                    }]}
                  >
                    <Input placeholder="请输入机器人webhook地址" />
                  </Form.Item>
                  {/* <Form.Item
                  name="wechatWebHookCondition"
                  label="推送条件"
                  initialValue={30}
                >
                  <Radio.Group >
                    <Radio value={30}>设置短期掉线</Radio>
                    <Radio value={480}>设置长期掉线</Radio>
                  </Radio.Group>
                </Form.Item> */}
                  <Form.Item
                    name="alertEnabled"
                    label="异常通知时间设置"
                    initialValue={false}
                    style={{marginBottom:0}}
                  >
                    <Radio.Group name="WECHATGROUP" onChange={noticeChange}>
                      <Radio value={true}>启用</Radio>
                      <Radio value={false}>禁用</Radio>
                    </Radio.Group>
                  </Form.Item>
                  <Form.Item
                    noStyle
                    shouldUpdate={(prevValues, currentValues) =>
                      prevValues.resolution !== currentValues.resolution
                    }
                  >
                    {({ getFieldValue }) => {
                      return wechatGroup?.alertDate ? (
                        <>
                          <div className="pop">
                            <div className="mask">
                              <div className="content" onClick={() =>{
                                wechatGroup.alertTime = [moment(wechatGroup?.alertStartTime,'HH:mm:ss'), moment(wechatGroup?.alertEndTime,'HH:mm:ss')];
                                wechatGroup.alertType = "WECHATGROUP";
                                form4.setFieldsValue(wechatGroup);
                                setCheckedList(wechatGroup.alertDate);
                                setIndeterminate(!!wechatGroup.alertDate.length && wechatGroup.alertDate.length < weeks.length);
                                setCheckAll(wechatGroup.alertDate.length === weeks.length);
                                setAccess("edit");
                                setDialogVisible(true);
                              }} 
                              >
                                <span className="button">
                                  <EditOutlined style={{ fontSize: 32 }} />
                                  <span style={{ display: 'block', marginTop: 5, fontSize: 16 }}>编辑</span>
                                </span>
                              </div>
                            </div>
                            <Row>
                              <Col span={6}>预警日期:</Col>
                              <Col span={16}>{wechatGroup.alertDate.map(date => { return <Tag color="blue" style={{ marginBottom: 5 }}>{weeksObject[date]}</Tag> })}</Col>
                            </Row>
                            <Row>
                              <Col span={6}>预警时间:</Col>
                              <Col span={16}>{wechatGroup.alertStartTime} - {wechatGroup.alertEndTime}</Col>
                            </Row>
                            <Row>
                              <Col span={6}>超时时间:</Col>
                              <Col span={16}>{wechatGroup.alertTriggerTime}</Col>
                            </Row>
                          </div>
                        </>
                      ) : null;
                    }}
                  </Form.Item>
                </Form>
              </TabPane>
            </Tabs>

          </TabPane>
          <TabPane tab={<span><DingdingOutlined />钉钉</span>} key="5">
            <Form {...layout1} ref={formRef} form={form3} onFinish={handleDingDingHookFinish}>
              <Form.Item name="orgId" style={{ display: 'none' }}></Form.Item>
              <Form.Item
                name="dingdingWebHook"
                label="机器人webhook地址"
                rules={[{ required: true, max: 256 }, {
                  validator: (rule, value, callback) => {
                    if (!value) {
                      callback();
                    }
                    if (IsURL(value)) {
                      callback();
                    } else {
                      callback("不是一个有效的地址");
                    }
                  },
                }]}
              >
                <Input placeholder="请输入机器人webhook地址" />
              </Form.Item>
              <Form.Item
                name="alertEnabled"
                label="异常通知时间设置"
                initialValue={false}
                style={{marginBottom:0}}
              >
                <Radio.Group name="DINGDING" onChange={noticeChange}>
                  <Radio value={true}>启用</Radio>
                  <Radio value={false}>禁用</Radio>
                </Radio.Group>
              </Form.Item>
              <Form.Item
                    noStyle
                    shouldUpdate={(prevValues, currentValues) =>
                      prevValues.resolution !== currentValues.resolution
                    }
                  >
                    {({ getFieldValue }) => {
                      return dingding?.alertDate ? (
                        <>
                          <div className="pop">
                            <div className="mask">
                              <div className="content" onClick={() =>{
                                dingding.alertTime = [moment(dingding?.alertStartTime,'HH:mm:ss'), moment(dingding?.alertEndTime,'HH:mm:ss')];
                                dingding.alertType = "DINGDING";
                                form4.setFieldsValue(dingding);
                                setCheckedList(dingding.alertDate);
                                setIndeterminate(!!dingding.alertDate.length && dingding.alertDate.length < weeks.length);
                                setCheckAll(dingding.alertDate.length === weeks.length);
                                setAccess("edit");
                                setDialogVisible(true);
                              }} 
                              >
                                <span className="button">
                                  <EditOutlined style={{ fontSize: 32 }} />
                                  <span style={{ display: 'block', marginTop: 5, fontSize: 16 }}>编辑</span>
                                </span>
                              </div>
                            </div>
                            <Row>
                              <Col span={6}>预警日期:</Col>
                              <Col span={16}>{dingding.alertDate.map(date => { return <Tag color="blue" style={{ marginBottom: 5 }}>{weeksObject[date]}</Tag> })}</Col>
                            </Row>
                            <Row>
                              <Col span={6}>预警时间:</Col>
                              <Col span={16}>{dingding.alertStartTime} - {dingding.alertEndTime}</Col>
                            </Row>
                            <Row>
                              <Col span={6}>超时时间:</Col>
                              <Col span={16}>{dingding.alertTriggerTime}</Col>
                            </Row>
                          </div>
                        </>
                      ) : null;
                    }}
                  </Form.Item>
            </Form>
          </TabPane>
        </Tabs>
        <Modal
          className={styles.timeSetDialog}
          destroyOnClose
          title="设备异常通知时间设置"
          visible={dialogVisible}
          onCancel={dialogClose}
          width={250}
          footer={[
            <>
              <Button type="default" onClick={dialogClose}>取消</Button>
              <Button type="primary" onClick={setTimeSubmit}>保存</Button>
            </>
          ]}
        >
          <Form {...layout2} ref={formRef} form={form4} onFinish={handleSetNoticeTime}>
            <Form.Item name="orgId" style={{ display: 'none' }}></Form.Item>
            <Form.Item name="alertType" style={{ display: 'none' }}></Form.Item>
            <span className="title">预警日期</span>
            <Form.Item
              name="alertDate"
              label=""
              rules={[{ required: true, message: '请选择预警日期' }]}
            >
              <Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} checked={checkAll}>全选</Checkbox>
              <CheckboxGroup options={weeks} value={checkedList} onChange={onDateChange} />
            </Form.Item>
            <span className="title">预警时间</span>
            <Form.Item name="alertStartTime" style={{ display: 'none' }}></Form.Item>
            <Form.Item name="alertEndTime" style={{ display: 'none' }}></Form.Item>
            <Form.Item
              name="alertTime"
              label=""
              rules={[{ required: true, message: '请输入预警时间' }]}
            >
              <TimePicker.RangePicker onChange={rangePickerChange} />
            </Form.Item>
            <span className="title">超时时间（掉线时间）</span>
            <Form.Item
              name="alertTriggerTime"
              label=""
            >
              <Form.Item noStyle name="alertTriggerHour" initialValue={0}>
                <InputNumber
                  min={0}
                  max={23}
                  defaultValue={0}
                  formatter={value => value > 9 ? value : `0${value}`}
                  style={{ width: 60 }}
                />
              </Form.Item>
              <Form.Item noStyle name="alertTriggerMinute" initialValue={15}>
                <InputNumber min={15} max={55} defaultValue={15} style={{ width: 60,marginLeft:-1}} />
              </Form.Item>
            </Form.Item>
          </Form>
        </Modal>
      </>
    );
  };

  return (
    <Modal
      className={styles.emailSetDialog}
      confirmLoading={loading}
      destroyOnClose
      title="设备异常通知设置"
      visible={modalVisible}
      {...modalFooter}
    >
      <Spin spinning={spinning}>
        {renderContent()}
      </Spin>
    </Modal>
  );
};

export default SetOrgModel;
